package com.koron.order.question.plugin;

import com.alibaba.fastjson.JSON;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.datadict.service.SysDataDictService;
import com.koron.common.core.business.datadict.utils.DataDictTool;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.order.question.bean.po.QuestionPo;
import com.koron.order.question.controller.QuestionController;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName QuestionWaitReviewPlugin
 * @description
 * @Author zhouj
 * @Date 2022/1/12 18:52
 */
@Slf4j
@RequestMapping("/question/plugin/waitReview/")
@RestController
@Api(tags = "重大问题报告工单-待审核插件")
public class QuestionReportReviewPlugin {

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Autowired
    private QuestionController questionController;

    @Autowired
    private SysDataDictService sysDataDictService;

    @Autowired
    private SystemFeignService systemFeignService;

    //部门分管领导审批审批 节点配置出口规则
    @PostMapping("/task1/submitter")
    public Response<List<WorkflowUser>> submitter1(@RequestBody SubmitterParam submitterParam) {

        String formVariables = submitterParam.getFormVariables();
        List<WorkflowUser> workflowUsers = submitterParam.getUsers();

        //返回对象
        List<WorkflowUser> result = new ArrayList<>();

        QuestionPo questionPo = getBussinessBean(submitterParam);
        /*
                节点1的过滤处理  部门分管领导审批审批
                1、处理人	编制节点选择的人
                2、必须变更审批人的节点	无
                3、选人组件过滤规则	无
                4、自动过滤规则	无
                5、操作类型	驳回、沟通、转办
                */
        //设备管理单位
        String deptManage = questionPo.getDeptManage();
        String deptManageName = questionPo.getDeptManageName();

        List<String> orgIdList = new ArrayList<>();
        orgIdList.add(deptManage);

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        //先将岗位转化为对应的人员列表，利用人员的单位==重大问题报告工单的设备管理单位
        PostUserQuery postUserQuery = new PostUserQuery();
        postUserQuery.setPostIdList(gwIdList);
        postUserQuery.setOrgIdList(orgIdList);
        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        //转换为返回对象
        convertUser(postUserVos, result);

        return Response.ok(result);
    }

    //主办部门负责人审批 节点配置出口规则
    @PostMapping("/task2/submitter")
    public Response<List<WorkflowUser>> submitter2(@RequestBody SubmitterParam submitterParam) {
        /*
        1、处理人	部门总经理（岗位）
        2、必须变更审批人的节点	无
        3、选人组件过滤规则	无
        4、自动过滤规则	只发送给编制人所在部门的部门总经理
        5、操作类型	驳回、沟通、转办
        */
        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //主要根据专业来筛选
        QuestionPo questionPo = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        List<String> arrayList = new ArrayList<>();

        PostUserQuery postUserQuery = new PostUserQuery();

        String deptId = questionPo.getDeptId();

        Response<OrgBean> orgBeanResponse = systemFeignService.queryDeptByOrgId(deptId);
        OrgBean data = orgBeanResponse.getData();
        Assert.notNull(data);

        postUserQuery.setPostIdList(gwIdList);
        postUserQuery.setParentOrgIdList(Arrays.asList(new String[]{data.getId()}));

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);
    }

    //技术部专业管理审批 节点配置出口规则
    @PostMapping("/task3/handler")
    public Response<List<WorkflowUser>> submit3(@RequestBody SubmitterParam submitterParam) {
        //节点3的过滤处理

        /*
        1、处理人	生产技术部机械管理（岗位）、生产技术部通讯管理（岗位）
           生产技术部电气管理（岗位）、生产技术部自动化管理（岗位）
        2、必须变更审批人的节点	无
        3、自动过滤规则	根据填单时所选择的专业，自动发送至相关专业管理审批
        */

        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //主要根据专业来筛选
        QuestionPo questionPo = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        //根据重大问题报告工单的专业--通过字典转化为中文
        String major = questionPo.getMajor();
        String major_dict = major;

        //下面为获取可用列表
        Map<String, String> dataDictByCode = DataDictTool.getDataDictByCode("publicDictionary", "common_major");
        major_dict = dataDictByCode.get(major);

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        List<String> arrayList = new ArrayList<>();

        PostUserQuery postUserQuery = new PostUserQuery();

        postUserQuery.setPostIdList(gwIdList);

        postUserQuery.setPostName(major_dict);

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);

    }

    //技术部总经理审批 节点配置出口规则
    @PostMapping("/task4/submitter")
    public Response<List<WorkflowUser>> submit4(@RequestBody SubmitterParam submitterParam) {
        //节点3的过滤处理

        /*
        1、处理人	部门总经理（岗位）
        2、必须变更审批人的节点	无
        3、自动过滤规则	只发送至生产技术部的部门总经理
        */

        List<WorkflowUser> workflowUsers = submitterParam.getUsers();

        QuestionPo questionPo = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        List<String> arrayList = new ArrayList<>();

        PostUserQuery postUserQuery = new PostUserQuery();

        postUserQuery.setPostIdList(gwIdList);

        postUserQuery.setOrgName("生产技术部");

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);

    }


    //设备所属站负责人 节点配置出口规则
    @PostMapping("/task5/handler")
    public Response<List<WorkflowUser>> submit5(@RequestBody SubmitterParam submitterParam) {
        /*
        1、处理人	设备所属站负责人：站长（岗位）
        2、必须变更审批人的节点	无
        3、自动过滤规则	自动发送至填单时所选的设备所属单位的站长
        4、操作类型	驳回、沟通、转办
        5、通知方式	待办
        6、流转方式	与技术部专业管理人员共同会签
        */

        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //填单时所选的设备所属单位
        QuestionPo questionPo = getBussinessBean(submitterParam);

        List<WorkflowUser> result = new ArrayList<>();

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        List<String> arrayList = new ArrayList<>();

        PostUserQuery postUserQuery = new PostUserQuery();

        postUserQuery.setPostIdList(gwIdList);

        postUserQuery.setOrgId(questionPo.getDeptManage());

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);

    }

    //设备管理部审批 节点配置出口规则
    @PostMapping("/task6/submitter")
    public Response<List<WorkflowUser>> submit6(@RequestBody SubmitterParam submitterParam) {
        /*
        1、处理人	设备所属部门负责人：部门总经理（岗位）
        2、必须变更审批人的节点	无
        3、自动过滤规则	自动发送至填单时所选的设备所属部门的部门总经理
        4、操作类型	驳回、沟通、转办
        5、通知方式	待办
        6、流转方式	与技术部总经理共同会签
        */

        List<WorkflowUser> workflowUsers = submitterParam.getUsers();
        //填单时所选的设备所属部门
        QuestionPo questionPo = getBussinessBean(submitterParam);

        Response<OrgBean> orgBeanResponse = systemFeignService.queryDeptByOrgId(questionPo.getDeptManage());

        List<WorkflowUser> result = new ArrayList<>();

        /*name code type*/
        //先分类
        List<WorkflowUser> gwList = workflowUsers.stream().filter(p -> 2 == p.getType()).collect(Collectors.toList());

        Assert.notEmpty(gwList, "配置的岗位不能为空");

        //分别通过各自id/code进行查询，或者过滤，最终转化为人员
        List<String> gwIdList = gwList.stream().map(WorkflowUser::getCode).collect(Collectors.toList());

        List<String> arrayList = new ArrayList<>();

        PostUserQuery postUserQuery = new PostUserQuery();

        postUserQuery.setPostIdList(gwIdList);

        if (orgBeanResponse.getData() != null) {
            postUserQuery.setParentOrgIdList(Arrays.asList(new String[]{orgBeanResponse.getData().getId()}));
        }

        //拿到岗位下的人
        List<PostUserVo> postUserVos = getPostList(postUserQuery);

        convertUser(postUserVos, result);

        return Response.ok(result);

    }


    private QuestionPo getBussinessBean(SubmitterParam submitterParam) {
        return JSON.parseObject(submitterParam.getFormVariables(), QuestionPo.class);
    }

    private List<PostUserVo> getPostList(PostUserQuery postUserQuery) {
        Response<List<PostUserVo>> listResponse = systemFeignService.queryPostList(postUserQuery);
        List<PostUserVo> postUserVos = listResponse.getData();
        return postUserVos;
    }

    private void convertUser(List<PostUserVo> postUserVos, List<WorkflowUser> result) {
        //转换为返回对象
        if (CollectionUtils.isEmpty(postUserVos)) {
            return;
        }
        for (PostUserVo postUserVo : postUserVos) {
            WorkflowUser workflowUser = new WorkflowUser();
            workflowUser.setCode(postUserVo.getUserAccount());
            workflowUser.setName(postUserVo.getUserName());
            result.add(workflowUser);
        }
    }

}
